<?php
include('../db_connect.php');

$add_ulink=true;

if($_POST["ulinkID"] == ""){
	$add_ulink=false;
    echo "Sorry, could not validate ULink ID.";
    return;
}

if(ereg('[^A-Za-z0-9]',$_POST['ulinkID'])){
	$add_ulink=false;
    echo "Sorry, could not validate ULink ID. Illegal characters were found.";
    return;
}
$str_length=strlen($_POST['ulinkID']);
if($str_length<7 || $str_length >10){
    echo "Sorry, could not validate ULink ID.";
    return;
}

if($_POST["studentID"] == "" || !is_numeric($_POST['studentID'])){
	$add_ulink=false;
    echo "Sorry, could not validate Student ID.";
    return;
}
$str_length=strlen($_POST['studentID']);
if($str_length<6 || $str_length > 10){
    echo "Sorry, could not validate Student ID.";
    return;
}

$ulink_id= htmlspecialchars(stripslashes(strip_tags( $_POST["ulinkID"])));
$student_id=htmlspecialchars(stripslashes(strip_tags( $_POST["studentID"])));
$fb_user_id=$_POST['user_id'];

//make sure this student id doesn't already exist
$sql="select user_id from fb_users where student_id=$student_id";
$result= $db->Execute($sql);
if($result->fields['user_id'])
{
    $add_ulink=false;
    echo "Sorry, this student ID is taken. Please contact Reach or try again.";
    return;
}

//make sure this ulink id doesn't already exist
$sql="select user_id from fb_users where ulink_id='$ulink_id'";
$result2= $db->Execute($sql);
if($result2->fields['user_id'])
{
    $add_ulink=false;
    echo "Sorry, this ULink ID is taken. Please contact Reach or try again.";
    return;
}

//we are validated, send verification email here
if($add_ulink){
    //generate confirm code
    $confirm_code=md5(uniqid(rand()));
    $sql="update fb_users set confirm_code='$confirm_code' where user_id=$fb_user_id";
    $db->Execute($sql);

    $subject= "Study Buddies Email Verification";
    $message= "Welcome to Study Buddies! \n\nThis message has been sent to verify your ULink ID \"$ulink_id\" with the Study Buddies application provided by REACH. \n\nPlease click the following link to verify your ID: http://apps.facebook.com/studybuddies/confirmation.php?passkey=$confirm_code&fb_id=$fb_user_id&ulink=$ulink_id&student_id=$student_id";
    $headers = "From: REACH\r\n" . "X-Mailer: php";
    mail($ulink_id. "@louisville.edu", $subject,$message,$headers);
    echo "<b>Thank you! A verification email has been sent to $ulink_id@louisville.edu. Please click the verification link which should arrive shortly.</b>";
}

?>
